package com.rainng.coursesystem.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.rainng.coursesystem.dao.mapper.DeviceMapper;
import com.rainng.coursesystem.model.shitong.*;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import org.apache.http.client.utils.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DeviceService extends BaseService {

    @Resource
    private DeviceMapper mapper;


    @Resource
    private UserService userService;

    public ResultVO queryDevice(DeviceVo vo) {
        Page<Object> pageParam = new Page<>(vo.getPageNum(), vo.getPageSize());
        if(vo.getSpecial() == 1){
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, 15);
            Date result = calendar.getTime();
            String vtime = DateUtil.format(result, "yyyy-MM-dd HH:mm:ss");
            vo.setValidEndTime(vtime);
        }

        IPage<Object> res = mapper.queryDevice(vo, pageParam);
        return result(res.getRecords());
    }

    public ResultVO countDevice(DeviceVo vo) {
        int res = mapper.countDevice(vo);
        return result(res);
    }


    public ResultVO saveDevice(DeviceSaveVo vo) {
        int res = mapper.saveDevice(vo);
        return result("存储成功");
    }

    public ResultVO deleteDevice(String id) {
        int res = mapper.deleteDevice(id);
        return result("删除成功");
    }


    public ResultVO updateDevice(String id, DeviceSaveVo vo) {
        int res = mapper.updateDevice(id, vo);
        return result("更新成功");
    }


    public ResultVO updateStateDevice(String id, DeviceStateUpdateVo vo) {

        String deviceNo = mapper.selectDeviceNoById(Integer.valueOf(id));
        String state = mapper.selectStateById(Integer.valueOf(id));

        if (!state.equals(vo.getDeviceStatus())) {
            String message = "设备状态 " + state + " 变更为 " + vo.getDeviceStatus();
            insertDeviceLogs(deviceNo, message, null);
        }


        int res = mapper.updateStateDevice(id, vo);
        return result("更新成功");
    }

    public ResultVO updateValidDevice(String id, DeviceValidTimeUpdateVo vo) {
        String validendtime = vo.getValidEndTime();
        String validstarttime = vo.getValidStartTime();
        String deviceNo = mapper.selectDeviceNoById(Integer.valueOf(id));
        //形式主义
        if (true) {
            String emessage = "";
            String et = mapper.selectEndtimeById(Integer.valueOf(id));
            if (!validendtime.equals(et)) {
                emessage = "有效期结束时间 " + et + " 变更为 " + validendtime;
            }
            String smessage = "";
            String st = mapper.selectStarttimeById(Integer.valueOf(id));
            if (!validstarttime.equals(st)) {
                smessage = "有效期开始时间 " + st + " 变更为 " + validstarttime;
            }
            if ((!validendtime.equals(et)) || (!validstarttime.equals(st))) {
                insertDeviceValidTimeLogs(deviceNo, smessage, emessage, null);
            }
        }
        int res = mapper.updateValidTimeDevice(id, vo);

        Integer value = Integer.valueOf(id);
        String state = mapper.selectStateById(value);
        if ("可用".equals(state)) {
            String vet = mapper.selectValidEndTimeById(value);
            if (StrUtil.isNotEmpty(vet)) {
                Date n = new Date();
                Date date1 = null;
                try {
                    date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(vet);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                int result = date1.compareTo(n);
                if (result < 0) {
                    DeviceStateUpdateVo stateVo = new DeviceStateUpdateVo();
                    stateVo.setDeviceStatus("弃用");
                    int j = mapper.updateStateDevice(id.toString(), stateVo);

                    System.out.println("???!!!");
                    String message = "设备状态 可用 变更为 弃用";
                    insertDeviceLogs(deviceNo, message, null);
                }
            }
        }
        if ("弃用".equals(state)) {
            String vet = mapper.selectValidEndTimeById(value);
            if (StrUtil.isNotEmpty(vet)) {
                Date n = new Date();
                Date date1 = null;
                try {
                    date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(vet);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                int result = date1.compareTo(n);
                if (result > 0) {
                    DeviceStateUpdateVo stateVo = new DeviceStateUpdateVo();
                    stateVo.setDeviceStatus("可用");
                    int j = mapper.updateStateDevice(id.toString(), stateVo);

                    System.out.println("???!!!");
                    String message = "设备状态 弃用 变更为 可用";
                    insertDeviceLogs(deviceNo, message, null);
                }
            }
        }


        return result("更新成功");
    }

    //定时任务方法
    public void refreshStatus() {
        List<Integer> ids = mapper.selectDeviceIdsByInUse();

        for (Integer id : ids) {
            String state = mapper.selectStateById(id);
            if ("可用".equals(state)) {
                String vet = mapper.selectValidEndTimeById(id);
                if (StrUtil.isNotEmpty(vet)) {
                    Date n = new Date();
                    Date date1 = null;
                    try {
                        date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(vet);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    int result = date1.compareTo(n);
                    if (result < 0) {
                        DeviceStateUpdateVo stateVo = new DeviceStateUpdateVo();
                        stateVo.setDeviceStatus("弃用");
                        int j = mapper.updateStateDevice(id.toString(), stateVo);
                        String deviceNo = mapper.selectDeviceNoById(Integer.valueOf(id));
                        System.out.println("???!!!");
                        String message = "设备状态 可用 变更为 弃用";
                        insertDeviceLogs(deviceNo, message, "system");
                    }

                }
            }
            if ("弃用".equals(state)) {
                String vet = mapper.selectValidEndTimeById(id);
                if (StrUtil.isNotEmpty(vet)) {
                    Date n = new Date();
                    Date date1 = null;
                    try {
                        date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(vet);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    int result = date1.compareTo(n);
                    if (result > 0) {
                        DeviceStateUpdateVo stateVo = new DeviceStateUpdateVo();
                        stateVo.setDeviceStatus("可用");
                        int j = mapper.updateStateDevice(id.toString(), stateVo);
                        String deviceNo = mapper.selectDeviceNoById(Integer.valueOf(id));
                        System.out.println("???!!!");
                        String message = "设备状态 弃用 变更为 可用";
                        insertDeviceLogs(deviceNo, message, "system");
                    }

                }
            }

        }

        return;
    }

    //日志变动记录
    public void insertDeviceLogs(String deviceNo, String message, String user) {
        String ctime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        //取session
        if (user == null) {
            ResultVO<Map<String, String>> vo = userService.getLoginStatusWithDepartment();
            user = vo.getData().get("username");

        }
        int k = mapper.saveDeviceLog(user, deviceNo, message, ctime);
    }


    //日志变动记录
    public void insertDeviceValidTimeLogs(String deviceNo, String starttimemessage, String endtimemessage, String user) {
        String ctime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        //取session
        if (user == null) {
            ResultVO<Map<String, String>> vo = userService.getLoginStatusWithDepartment();
            user = vo.getData().get("username");

        }
        int k = mapper.saveDeviceValidTimeLog(user, deviceNo, starttimemessage, endtimemessage, ctime);

    }


    public ResultVO queryLogsDevice(DeviceLogsVo vo) {
        Page<Object> pageParam = new Page<>(vo.getPageNum(), vo.getPageSize());
        IPage<Object> res = mapper.queryDeviceLogs(vo, pageParam);
        return result(res.getRecords());
    }

    public ResultVO countLogsDevice(DeviceLogsVo vo) {
        int res = mapper.countDeviceLogs(vo);
        return result(res);
    }


    public ResultVO queryTimeLogsDevice(DeviceLogsVo vo) {
        Page<Object> pageParam = new Page<>(vo.getPageNum(), vo.getPageSize());
        IPage<Object> res = mapper.queryDeviceTimeLogs(vo, pageParam);
        return result(res.getRecords());
    }

    public ResultVO countTimeLogsDevice(DeviceLogsVo vo) {
        int res = mapper.countDeviceTimeLogs(vo);
        return result(res);
    }
    public ResultVO deviceQueryByParams(List<String> prjNames, List<String> measureRequirement) {
        List<DeviceVo> res = mapper.deviceQueryByParams(prjNames, measureRequirement);
        return result(res);
    }

}
